package com.fmy.security.handel;

import com.fmy.security.cache.CacheOnline;
import com.fmy.security.cache.Token;
import com.fmy.security.commons.tools.RequestTool;
import com.fmy.security.config.TokenProperties;
import com.fmy.security.config.filter.LoginTypeFilter;
import com.fmy.security.service.LoginHandler;
import com.fmy.security.service.TokenGenerate;
import com.fmy.security.service.login.CustAuthenticationHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @Author MR.fmy
 * @Description 登录成功处理类
 * @Date 2019/5/14 0014 10:05
 **/
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    private CacheOnline cacheOnline;
    private TokenGenerate tokenService;
    private LoginHandler loginHandler;
    private TokenProperties tokenProperties;

    public AuthenticationSuccessHandlerImpl(CacheOnline cacheOnline, TokenGenerate tokenService, LoginHandler loginHandler, TokenProperties tokenProperties) {
        this.cacheOnline = cacheOnline;
        this.tokenService = tokenService;
        this.loginHandler = loginHandler;
        this.tokenProperties = tokenProperties;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        String loginType = CustAuthenticationHolder.get().getAuthType();
        Token token = tokenService.generate(authentication, loginType, tokenProperties.getExpireTime());
        cacheOnline.set(token);
        //调用返回前辍
        loginHandler.resultPrefix();
        //数据返回
        RequestTool.responseWriter(response, HttpStatus.OK, loginHandler.resultSuccess(token));
    }

}
